import os
import os.path


def alter(file, old_str, new_str):
    """
    替换文件中字符串
    :param file:文件名
    :param old_str: 旧字符串
    :param new_str: 新字符串
    :return:
    """
    file_data = ""
    with open(file, "r", encoding="utf-8") as f:
        for line in f:
            if old_str in line:
                line = line.replace(old_str, new_str)
            file_data += line
    with open(file, "w", encoding="utf-8") as f:
        f.write(file_data)


if __name__ == '__main__':
    path = "D:\\pubQuestion"  # xml文件所在的目录，举例
    files = os.listdir(path)  # 获得文件夹下所有文件名
    for xmlFile in files:  # 遍历文件夹
        if not os.path.isdir(xmlFile):  # 判断是否是文件夹,不是文件夹才打开
            print
            xmlFile
            pass
        newStr = os.path.join(path, xmlFile)  # 文件路径
        file = newStr
        old_str = "pub_question"
        new_Str = "pubQuestion"
        alter(file, old_str, new_Str)
